<template>
    <el-dialog class="jzb-dialog" :title="title" :visible.sync="visibleDialog" :width="width" id="dept-dialog-choose" :close-on-click-modal="false" append-to-body v-dialogDrag>
        <el-container class="mainer">
            <el-aside width="250px" class="jzb-area">
                <div class="hd">单位列表</div>
                <div class="hdflex h40"><el-input placeholder="搜索单位关键字" v-model="filterComText" size="mini"></el-input></div>
                <div class="bd">
                    <el-tree :data="comList" :props="comProps" @node-click="changeCom" node-key="comId" ref="comTree" :filter-node-method="filterComNode"></el-tree>
                </div>
            </el-aside>
            <el-aside width="300px" class="jzb-area">
                <div class="hd">部门列表（{{selectComName.length>10?(selectComName.substring(0,10)+'...'):selectComName}}）</div>
                <div class="hdflex h40"><el-input placeholder="搜索部门关键字" v-model="filterDeptText" size="mini"></el-input></div>
                <div class="bd">
                    <el-tree :data="deptTreeList" :props="deptProps" ref="dataTree" show-checkbox @check-change="changeDept" :check-on-click-node="true" 
                        node-key="depId" :default-expanded-keys="['all']" :filter-node-method="filterDeptNode"></el-tree>
                </div>
            </el-aside>
            <el-main class="jzb-colflex">
                <div class="hd">已选部门（{{choosedList.length}}）</div>
                <div class="bd pl-10 pr-10">
                    <el-tag-group v-model="choosedList" :isGroup="true" @change="setDeptCheckedKeys" labelName="depName" valueName="depId"></el-tag-group>
                </div>
            </el-main>
        </el-container>
        <el-footer height="auto" class="jzb-dialog-footer" slot="footer">
            <div class="content">已选部门：{{choosedList.length}}</div>
            <button type="button" class="jzb-button" @click="saveData"><span class="icon icon-ok"></span>保 存</button>
            <button type="button" class="jzb-button" @click="visibleDialog = false"><span class="icon icon-undo"></span>取 消</button>
        </el-footer>
    </el-dialog>
</template>
<script>
/** 组件功能：从本单位和参建单位选择部门列表
* 传入：props
* 输出：[{depId,depName,comId,comName,...},...]
*/
import _ from 'lodash';
import elTagGroup from '@/components/public/el-tag-group.vue';
import {GetRequestParams} from "@/utils/utils.js";
import {company,depart} from "@/api/org.js";
export default {
    name:'com-choose-dept',
    components: {
        elTagGroup,
    },
    props:{
        // 配置项
        comId:{ type: String, default: '' }, //单位ID
        title:{ type: String, default: '选择部门' }, //对话框title
        visible:{ type: Boolean, default: false }, //对话框显示
        ifInit:{ type: Boolean, default: false }, //是否初始化本单位信息
        width:{ type: String, default: '1000px' }, //对话框宽度
        value:{ type: Array, default:()=>{return []}}, //用户列表默认选中
        returnValue:{ type: Boolean, default:false}, //是否必须选中值
    },
    data(){
        return {
            //1.基本
            visibleDialog:false,
            selectComId:'',
            selectComName:'',
            choosedList:[],
            comList:[],
            deptTreeList:[], //部门树列表
            deptList:[], //部门一维列表
            dataList:[],
            comProps:{
                value:'comId',             // ID字段名
                label: 'comName',         // 显示名称
                children: 'children'    // 子级字段名
            },
            deptProps:{
                value:'depId',             // ID字段名
                label: 'depName',         // 显示名称
                children: 'children'    // 子级字段名
            },
            filterComText:'',
            filterDeptText:'',
        };
    },    
    watch:{
        value(val){
            this.dataList = [...val];
        },
        visible(val){
            if(val) this.openComChooseData();
        },
        visibleDialog(val){
            if(!val) this.$emit('close');
        },
        filterComText(val) {
            this.$refs.comTree.filter(val.trim());
        },
        filterDeptText(val) {
            this.$refs.dataTree.filter(val.trim());
        },
    },
    mounted(){
        if(this.ifInit){
            this.GetBudComList();
        }
    },
    methods:{
        //1.1 组件打开时初始化
        openComChooseData(){
            this.choosedList = [...this.dataList];
            this.visibleDialog = true;
            if(!this.ifInit){
                this.GetBudComList();
            }
        },
        //2.1 获取参建单位+本单位列表
        GetBudComList(){
            let params = {
                comId:this.comId||this.$store.state.comId||GetRequestParams().comid,
                includeSelf:true,
            }
            company.listBudBrief(params).then(res=>{
                if(res.code='30000'){
                    this.comList = [res.com,...res.buds];
                    this.selectComId = params.comId;
                    this.selectComName = this.comList[0].comName;
                    this.GetDepartList();
                }
            })
        },
        //2.2 切换单位时
        changeCom(node){
            this.selectComId = node.comId;
            this.selectComName = node.comName;
            this.GetDepartList();
        },
        //2.6 关键字搜索
        filterComNode(value, data) {
            if (!value) return true;
            return data.comName.indexOf(value) !== -1;
        },
        //3.1 获取部门列表
        GetDepartList(){
            let params = {
                comId:this.selectComId,
            }
            depart.list(params).then(res=>{
                if(res.code='30000'){
                    this.deptTreeList = [{depId:'all',depName:'全部',children:res.list}];
                    this.deptList = [];
                    this.deepDeptList(res.list);
                    this.setDeptCheckedKeys();
                }
            })
        },
        //3.2 获取this.deptList：选中单位下的部门一维数组[{comId,comName,depId,depName,depPid}]
        deepDeptList(deptlist,depPid = 'all'){
            _.each(deptlist,item=>{
                this.deptList.push({
                    comId:this.selectComId,
                    comName:this.selectComName,
                    depId:item.depId,
                    depName:item.depName,
                    depPid:depPid,
                })
                if(item.children &&item.children.length>0){
                    this.deepDeptList(item.children,item.depId);
                }
            })
        },
        //3.3 选中部门事件
        changeDept(data, checked, indeterminate){
            //已选列表 choosedList = choosedList - deptList + checkedList - childrenList;
            this.choosedList = _.pullAllBy(this.choosedList, this.deptList, 'depId'); // - deptList; 已选列表减去选中单位所有部门
            let checkedList = _.intersectionBy(this.deptList,this.$refs.dataTree.getCheckedNodes(),'depId'); //获取单位下已选部门，并和this.deptList做交集处理以便获取单位信息和部门pid
            this.choosedList = _.uniqBy(_.concat(this.choosedList, checkedList), 'depId'); //+checkedList;并去重
            this.choosedList = this.choosedList.filter(item => (item.depPid=='all'||!this.choosedList.some(dept=>dept.depId==item.depPid)))//-childrenList;部门被选中，应减去子部门列表
        },
        //3.5 设置默认选中值
        setDeptCheckedKeys(){
            let keys = [...this.choosedList].filter(dept=>dept.comId==this.selectComId).map(dept=>dept.depId);
            this.$refs.dataTree.setCheckedKeys(keys);
        },
        //3.6 关键字搜索
        filterDeptNode(value, data) {
            if (!value) return true;
            return data.depName.indexOf(value) !== -1;
        },
        //4.保存数据
        saveData(){
            if(this.returnValue && this.choosedList.length==0 ){
                this.$layer.msg('请选择部门');
                return;
            }
            this.$emit('input',this.choosedList);
            this.$emit('change',this.choosedList);
            this.visibleDialog = false;
        },
    },
};
</script>
<style lang="less" scoped>
@import "~@/assets/style/base.css";
@import "~@/assets/style/common.less";
.mainer{min-height:500px;overflow:auto;border:1px solid #ddd;}
</style>